import React, { useContext, useState } from 'react';
import { Grid, Image } from 'antd';
import { ConfigContext } from '../../configProvider';
import './index.less';
import IconFont from '../../iconfont';
interface ImageAdderProps {
  IMG_MAX_COUNT: number;
  COLUMN_MAX_COUNT: 3 | 4 | 6 | 8;
  imgsList: string[];
  onChangeImgs: (newImgsList: string[]) => void;
}
// {/* 选择并添加图片 */}
const ImageAdder: React.FC<ImageAdderProps> = ({
  IMG_MAX_COUNT,
  COLUMN_MAX_COUNT,
  imgsList,
  onChangeImgs,
}) => {
  if (IMG_MAX_COUNT === undefined) {
    IMG_MAX_COUNT = 9;
  }
  if (COLUMN_MAX_COUNT === undefined) {
    COLUMN_MAX_COUNT = 3;
  }
  imgsList.splice(IMG_MAX_COUNT);

  //添加图片
  const addImg = (imgs: string[]) => {
    console.log('addImg');
    var newImgsList = [...imgsList].concat(imgs);
    if (newImgsList.length > IMG_MAX_COUNT) {
      newImgsList.splice(IMG_MAX_COUNT);
    }
    onChangeImgs(newImgsList);
  };

  //删除指定的图片
  const deleteImg = (index: number) => {
    console.log('deleteImg' + index);
    var imgs = [...imgsList];
    var newCImg = [];
    for (let i = 0; i < imgs.length; i++) {
      if (i != index) {
        newCImg.push(imgs[i]);
      }
    }
    onChangeImgs(newCImg);
  };

  const handleFileUpload = (event) => {
    console.log(event.target.files);
    const files: File[] = Array.from(event.target.files);
    const imgs = files.map((value) => URL.createObjectURL(value));
    addImg(imgs);
  };

  return (
    <div
      className="image-adder-container"
      style={{
        width: `${200 * COLUMN_MAX_COUNT}px`,
        'grid-template-columns': `${'1fr '.repeat(COLUMN_MAX_COUNT)}`,
      }}
    >
      {imgsList.map((src: string, index: number) => (
        <div className="img-container">
          <Image src={src} className="comment-img"></Image>
          <div
            className="delete-btn"
            onClick={() => {
              deleteImg(index);
            }}
          >
            <IconFont name="close-circle-filled" size={32} color="rgba(255,0,0,0.6)"></IconFont>
          </div>
        </div>
      ))}

      {imgsList.length < IMG_MAX_COUNT && (
        <label className="img-container adder-icon">
          {/* 触发添加图片的加号 */}
          <IconFont name="photo" color="rgb(211, 176, 243)" size={120} />
          添加图片
          <input type="file" onChange={handleFileUpload} className="add-img-btn" multiple />
        </label>
      )}
    </div>
  );
};
export default ImageAdder;
